package common.adapters;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import common.managers.IImageManager;

public abstract class AbstractPagerAdapter<T> extends PagerAdapter {
	
	private Context context;
	private Cursor cursor;
	private String[] columnNames;
	private int[] viewId;
	private IImageManager imageManager;

	public AbstractPagerAdapter(Context ctx, Cursor cursor, IImageManager imageManager, int[] viewId,
			String[] columnNames){
		this.context = ctx;
		this.cursor = cursor;
		this.imageManager = imageManager;
		this.viewId = viewId;
		this.columnNames = columnNames;
	}
	
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		View convertView = View.inflate(context, getResources(), null);
		cursor.moveToPosition(position);
		for (int i = 0; i < viewId.length; i++) {
			View view = convertView.findViewById(viewId[i]);
			if (view instanceof TextView) {
				TextView textView = (TextView) view;
				String data = cursor.getString(cursor.getColumnIndex(columnNames[i]));
				if (data != null && !data.equals("")) {
					textView.setVisibility(View.VISIBLE);
					textView.setText(data);
				} else {
					textView.setVisibility(View.GONE);
				}
			}

			if (view instanceof ImageView) {
				ImageView imageView = (ImageView) view;
				String data = cursor.getString(cursor.getColumnIndex(columnNames[i]));
				if (data != null && !data.equals("")) {
					imageView.setVisibility(View.VISIBLE);
					imageManager.loadImage(data, imageView);
				} else {
					imageView.setImageDrawable(null);
				}
			}
		}
		((ViewPager) container).addView(convertView, 0);
		return convertView;
	}
	
	@Override
	public void destroyItem(ViewGroup container, int position, Object view) {
		((ViewPager) container).removeView((View) view);
	}

	@Override
	public int getCount() {
		return cursor.getCount();
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view.equals(object);
	}

	public abstract int getResources();
}
